package com.party.admin.web.controller.crowdfund;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.admin.biz.crowdfund.AnalyzeBizService;
import com.party.admin.web.annotation.UserOperate;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.output.crowdfund.AnalyzeOutput;
import com.party.admin.web.dto.output.crowdfund.TypeCountOutput;
import com.party.common.paging.Page;
import com.party.common.utils.DateUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.*;
import com.party.core.model.label.Label;
import com.party.core.model.log.BehaviorType;
import com.party.core.model.records.UpRecords;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.*;
import com.party.core.service.label.ILabelService;
import com.party.core.service.records.IUpRecordsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 众筹分析控制器
 * Created by wei.li
 *
 * @date 2017/7/10 0010
 * @time 14:31
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "/crowdfund/analyze")
public class AnalyzeController {

    @Autowired
    private AnalyzeBizService analyzeBizService;

    @Autowired
    private IAnalyzeService analyzeService;

    @Autowired
    private IProjectLabelService projectLabelService;

    @Autowired
    private ILabelService labelService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private IUpRecordsService upRecordsService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    ISupportService supportService;

    protected static Logger logger = LoggerFactory.getLogger(AnalyzeController.class);

    /**
     * 众筹分析列表
     *
     * @param projectAnalyze 众筹分析
     * @return 交互数据
     */
    @RequestMapping(value = "list")
    public ModelAndView list(ProjectAnalyze projectAnalyze) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/analyzeList");
        if (projectAnalyze.getTargetId() != null && projectAnalyze.getTargetId().length() > 10) {
            String[] tagIds = projectAnalyze.getTargetId().split(",");
            if (tagIds.length > 0)//对活动ID做变形处理
                projectAnalyze.setTargetId(tagIds[0]);
        } else {
            projectAnalyze.setTargetId(null);
        }
        List<String> dateList = analyzeBizService.dateStringList();
        List<Label> labelList = labelService.list(new Label());
        projectAnalyze.setPayType(0);
        TypeCountOutput countOutput = analyzeBizService.countList(projectAnalyze);//普通众筹统计
        projectAnalyze.setPayType(1);
        TypeCountOutput directCount = analyzeBizService.countDirectList(projectAnalyze);//直接付款众筹统计
        modelAndView.addObject("dateList", JSONObject.toJSON(dateList));
        modelAndView.addObject("labelList", JSONObject.toJSON(labelList));//标签列表（参与状态）
        modelAndView.addObject("count", countOutput);
        modelAndView.addObject("directCount", directCount);
        modelAndView.addObject("projectAnalyze", projectAnalyze);
        projectAnalyze.setPayType(null);
        Double totalAmount = projectService.sumForActualAmount(projectAnalyze,0);
        modelAndView.addObject("totalAmount", totalAmount);
        return modelAndView;
    }

    /**
     * 众筹分析-直接付款列表
     *
     * @param projectAnalyze 众筹分析
     * @return 交互数据
     */
    @RequestMapping(value = "directPayList")
    public ModelAndView directPayList(ProjectAnalyze projectAnalyze) {
        Integer isSuccess = projectAnalyze.getIsSuccess();
//        projectAnalyze.setIsSuccess(1);//只查询支付成功的直接支付众筹项目
        ModelAndView modelAndView = new ModelAndView("crowdfund/analyzeDirectPayList");
        List<String> dateList = analyzeBizService.dateStringList();
        TypeCountOutput directCount = analyzeBizService.countDirectList(projectAnalyze);//直接付款众筹统计
        projectAnalyze.setPayType(0);
        projectAnalyze.setIsSuccess(null);
        TypeCountOutput countOutput = analyzeBizService.countList(projectAnalyze);//普通众筹统计
        modelAndView.addObject("dateList", JSONObject.toJSON(dateList));
        modelAndView.addObject("count", countOutput);
        modelAndView.addObject("directCount", directCount);
        modelAndView.addObject("projectAnalyze", projectAnalyze);
        projectAnalyze.setPayType(1);
        projectAnalyze.setIsSuccess(isSuccess);
        Double totalAmount = projectService.sumForActualAmount(projectAnalyze,0);
        modelAndView.addObject("totalAmount", totalAmount);
        return modelAndView;
    }

    /**
     * 异步获取分析数据
     *
     * @param projectAnalyze
     * @param pageO
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/api/list")
    public Map<String, Object> ajaxData(ProjectAnalyze projectAnalyze, Page pageO) {
        List<AnalyzeOutput> outputList = analyzeBizService.list(projectAnalyze, pageO);
        //处理小于众筹时间开始的数据
        List<Date> dateDateList = analyzeBizService.dateList();
        for (AnalyzeOutput out : outputList) {
            String startDate = DateUtils.formatDate(out.getCreateDate(), "yy/MM/dd");
            Map<String, Double> map = out.getMoneyMap();
            for (Date dateData : dateDateList) {
                String strDate = DateUtils.formatDate(dateData, "yy/MM/dd");
                if (DateUtils.compareDate(dateData, out.getCreateDate()) == -1) {
                    if (!startDate.equals(strDate)) {
                        map.put(DateUtils.formatDate(dateData, "yy/MM/dd"), -1d);
                    }
                }
            }
        }
        Map<String, Object> ret = Maps.newHashMap();
        ret.put("data", outputList);
        ret.put("count", pageO.getTotalCount());
        ret.put("code", 0);
        return ret;
    }


    /***
     * 通过projectId 去更新 analyze表中，friend_num，poster_num，group_num，telephone_num的数据
     * @param projectId
     * @param type 类型 1代表更新friend_num，2代表更新poster_num，3代表更新group_num，4代表更新telephone_num
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateNum")
    public AjaxResult updateNum(String projectId, String type) {
        try {
            Integer num = 0;
            Analyze analyze = analyzeService.findByTargetId(projectId);
            if ("1".equals(type)) {
                analyze.setFriendNum(analyze.getFriendNum() + 1);
                num = analyze.getFriendNum();
            }
            if ("2".equals(type)) {
                analyze.setPosterNum(analyze.getPosterNum() + 1);
                num = analyze.getPosterNum();
            }
            if ("3".equals(type)) {
                analyze.setGroupNum(analyze.getGroupNum() + 1);
                num = analyze.getGroupNum();
            }
            if ("4".equals(type)) {
                analyze.setTelephoneNum(analyze.getTelephoneNum() + 1);
                num = analyze.getTelephoneNum();
            }
            analyzeService.update(analyze);
            return AjaxResult.success(num);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("更新Analyze异常", e);
        }
    }


    /**
     * 数据导出
     *
     * @param projectAnalyze 众筹分析
     * @param response       导出数据
     * @return 交互
     */
    @ResponseBody
    @UserOperate(moduleName = "众筹项目/主题-数据分析-众筹列表", behaviorType = BehaviorType.EXPORT)
    @RequestMapping(value = "listExport")
    public AjaxResult listExport(ProjectAnalyze projectAnalyze, HttpServletResponse response) {
        String fileName = "数据分析.xlsx";
        if (!Strings.isNullOrEmpty(projectAnalyze.getTargetId())) {
            Activity activity = activityService.get(projectAnalyze.getTargetId());
            fileName = activity.getTitle() + ".xlsx";
        } else if (!Strings.isNullOrEmpty(projectAnalyze.getEventId())) {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(projectAnalyze.getEventId());
            fileName = crowdfundEvent.getName() + ".xlsx";
        }

        List<AnalyzeOutput> outputList = analyzeBizService.list(projectAnalyze, null);
        try {
            String allPath = analyzeBizService.export(fileName, outputList, response, YesNoStatus.NO.getCode());
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出联合发起的众筹异常", e);
        }
        return AjaxResult.error("导出异常");
    }


    /**
     * 修改朋友状态
     *
     * @param projectId 项目编号
     * @param status    状态
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "changeFriend")
    public AjaxResult changeFriend(String projectId, Integer status) {
        AjaxResult ajaxResult = new AjaxResult();
        Analyze analyze = analyzeService.findByTargetId(projectId);
        analyze.setIsFriend(status);
        analyzeService.update(analyze);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    /**
     * 修改是否进群
     *
     * @param projectId 项目编号
     * @param status    状态
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "changeGroup")
    public AjaxResult changeGroup(String projectId, Integer status) {
        AjaxResult ajaxResult = new AjaxResult();
        Analyze analyze = analyzeService.findByTargetId(projectId);
        analyze.setIsGroup(status);
        analyzeService.update(analyze);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 修改是否做海报
     *
     * @param projectId 项目编号
     * @param status    状态
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "changePoster")
    public AjaxResult changePoster(String projectId, Integer status) {
        AjaxResult ajaxResult = new AjaxResult();
        Analyze analyze = analyzeService.findByTargetId(projectId);
        analyze.setIsPoster(status);
        analyzeService.update(analyze);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    /**
     * 我的标签列表
     *
     * @param projectId 项目编号
     * @return 交互数据
     */
    @RequestMapping(value = "labelView")
    public ModelAndView labelView(String projectId) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/distributionLabel");
        List<ProjectLabel> myLabelList = projectLabelService.findByProjectId(projectId);
        List<Label> labelList = labelService.list(new Label());
        modelAndView.addObject("myLabelList", myLabelList);
        modelAndView.addObject("labelList", labelList);
        modelAndView.addObject("projectId", projectId);
        return modelAndView;
    }


    /**
     * 保存标签
     *
     * @param id        标签集合
     * @param projectId 项目编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "labelSave")
    public AjaxResult labelSave(String id, String projectId) {
        AjaxResult ajaxResult = new AjaxResult();
        /*Set<String> idSet = Sets.newHashSet(Splitter.on(",").split(ids));*/
        String style = "";
        try {
            style = analyzeBizService.labelSave(id, projectId);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            return ajaxResult;
        }
        ajaxResult.setData(style);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    @ResponseBody
    @RequestMapping(value = "init")
    public AjaxResult init() {
        List<Analyze> list = analyzeService.list(new Analyze());
        for (Analyze analyze : list) {
            UpRecords upRecords = upRecordsService.getRecently(analyze.getTargetId());
            if (null != upRecords) {
                analyze.setRecentlyRecordDate(upRecords.getCreateDate());
                analyzeService.update(analyze);
            }
        }
        return AjaxResult.success();
    }


    @ResponseBody
    @RequestMapping(value = "initialization")
    public AjaxResult Initialization() {

        List<Project> projectList = projectService.inits();
        for (Project project : projectList) {
            Date now = new Date();
            Date startDate = DateUtils.addDay(now, -6);
            //最近七天的众筹金额
            Float sevenDaysNum = supportService.countBySupportDate(DateUtils.formatDate(startDate), DateUtils.formatDate(now),
                    project.getId());
            Analyze analyze = analyzeService.findByTargetId(project.getId());
            if (null != analyze) {
                analyze.setSevenDaysNum(sevenDaysNum);
                analyzeService.update(analyze);
            }
        }
        return AjaxResult.success();
    }
}
